package com.ruoyi.api.activiti.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.activiti.domain.HistoricActivity;
import com.ruoyi.activiti.service.IProcessService;
import com.ruoyi.api.activiti.domain.ApproveProcessVo;
import com.ruoyi.api.activiti.domain.DailyWorkBaseVO;
import com.ruoyi.api.activiti.service.ApplyAssetsReportService;
import com.ruoyi.api.activiti.service.ExpenseReportService;
import com.ruoyi.api.activiti.service.UsualWrokService;
import com.ruoyi.api.mqtt.MqttService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.result.ResultEnum;
import com.ruoyi.result.ResultView;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.util.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Author: LvKinfy
 * Time: 17:35
 * Desc: 常规日常工作：质量，安全，业务，档案，费用等
 */
@RestController
@RequestMapping("/api/usual")
public class UsualWorkController extends BaseController {
  @Value("${wspaas.dailyworkUrl}")
  private String dwUrl;
  @Autowired
  private ExpenseReportService expenseReportService;
  @Autowired
  private ApplyAssetsReportService applyAssetsReportService;

  @Autowired
  private UsualWrokService usualWrokService;
  @Autowired
  private IProcessService processService;
  @Autowired
  private ISysUserService sysUserService;

  @PostMapping("/{service}/commit")
  private Object commit(@PathVariable String service, @RequestBody JSONObject o) {
    if (null == o) {
      return ResultView.error(ResultEnum.CODE_2);
    }
    return usualWrokService.commit(o);
  }

  @PostMapping("/{service}/update")
  private Object update(@PathVariable String service, @RequestBody JSONObject o) {
    if (null == o) {
      return ResultView.error(ResultEnum.CODE_2);
    }
    StringBuilder sb = new StringBuilder();
    sb.append(dwUrl).append("/api/").append(service).append("/update");
    return HttpClientUtil.doPost(sb.toString(), o);
  }

  //局部更新
  @PostMapping("/{service}/update/{id}")
  private Object updateById(@PathVariable String service,@PathVariable String id, @RequestBody JSONObject o) {
    if (null == o) {
      return ResultView.error(ResultEnum.CODE_2);
    }
    StringBuilder sb = new StringBuilder();
    sb.append(dwUrl).append("/api/").append(service).append("/update/").append(id);
    return HttpClientUtil.doPost(sb.toString(), o);
  }

  //其他模块不开放删除
  @GetMapping("/{service}/del/{id}")
  private Object deleteById(@PathVariable String service,@PathVariable String id) {
    if (StringUtils.isEmpty(id)) {
      return ResultView.error(ResultEnum.CODE_2);
    }
    StringBuilder sb = new StringBuilder();
    sb.append(dwUrl).append("/api/").append(service).append("/del/").append(id);
    HttpClientUtil.doGet(sb.toString());
    return ResultView.ok();
  }


  @PostMapping("/list/{service}/{uid}/{time}/{dateorhour}")
  private Object listOfDateTime(@PathVariable String service, @PathVariable String uid, @PathVariable Long time, @PathVariable String dateorhour) {
    long endTime = time;
    if ("date".equalsIgnoreCase(dateorhour)) {
      endTime += 86400000;
    } else {
      endTime += 3600000;
    }
    StringBuilder sb = new StringBuilder();
    sb.append(dwUrl).append("/api/").append(service).append("/list/").append(uid).append("/").append(time).append("/").append(endTime);
    return HttpClientUtil.doGet(sb.toString());
  }

  //分页获取
  @PostMapping("/pagelist/{service}")
  private Object listByPage(@PathVariable String service,@RequestBody JSONObject o) {
    StringBuilder sb = new StringBuilder();
    sb.append(dwUrl).append("/api/").append(service).append("/page/sortlist");
    return HttpClientUtil.doPost(sb.toString(),o);
  }

  @PostMapping("/list/{service}/{loginName}")
  private Object listOfDate(@PathVariable String service, @PathVariable String loginName) {
    SysUser sysUser =sysUserService.selectUserByLoginName(loginName);
    if (sysUser != null) {
      StringBuilder sb = new StringBuilder();
      sb.append(dwUrl).append("/api/").append(service).append("/list/").append(sysUser.getUserId());
      Map<String, List<Long>> authIds = usualWrokService.getAuthIds(loginName);
      return HttpClientUtil.doPost(sb.toString(),authIds);
    }
    return ResultView.ok();
  }

  @PostMapping("/detail/{service}/{id}")
  private Object detail(@PathVariable String service, @PathVariable String id) {
    StringBuilder sb = new StringBuilder();
    sb.append(dwUrl).append("/api/").append(service).append("/detail/").append(id);
    return HttpClientUtil.doGet(sb.toString());
  }
  @Autowired
  private MqttService mqttService;
  @PostMapping("/submitApplyMobile/{service}/{id}/{loginName}/{projectId}")
  private ResultView submitApplyMobile(@PathVariable String service, @PathVariable String id, @PathVariable String loginName, @PathVariable String projectId) {
    if (null == service || service.equalsIgnoreCase(id)) {
      return ResultView.error(ResultEnum.CODE_2);
    }
    usualWrokService.submitApplyMobile(id, service, loginName);
    return ResultView.ok("启动审批流程");
  }

  /**
   * 审批列表
   * @param flag: 0 我的待审 1：我的已审 2.我的发起
   */
  @PostMapping("/applyList/{loginName}/{flag}")
  @ResponseBody
  public ResultView applyList(@PathVariable String loginName, @PathVariable String flag, String service) {
    if (flag.equalsIgnoreCase("0")) {
      List<DailyWorkBaseVO> allTodoTasksMobile = usualWrokService.todoTasksMobile(loginName, service);
      if(allTodoTasksMobile == null){
        allTodoTasksMobile=new ArrayList<>();
      }
      return ResultView.ok(allTodoTasksMobile);
    } else if (flag.equalsIgnoreCase("1")) {
      List<DailyWorkBaseVO> allDoneTasksMobile = usualWrokService.findDoneTasksMobile(loginName, service);
      if(allDoneTasksMobile == null){
        allDoneTasksMobile=new ArrayList<>();
      }
      return ResultView.ok(allDoneTasksMobile);
    } else if (flag.equalsIgnoreCase("2")) {
      List<DailyWorkBaseVO> dailyWorkBaseVOS = usualWrokService.appliedListMobile(loginName, service);
      if(dailyWorkBaseVOS == null){
        dailyWorkBaseVOS=new ArrayList<>();
      }
      return ResultView.ok(dailyWorkBaseVOS);
    }else if(flag.equalsIgnoreCase("3")){//抄送
      List<DailyWorkBaseVO> list = usualWrokService.applyCopyList(service, loginName);
      if(list == null){list=new ArrayList<>();}
      return ResultView.ok(list);
    }
    return ResultView.ok();
  }

  /**
   * 任务详情
   */
  @PostMapping("/taskDetail/{service}/{instanceId}/{taskId}")
  @ResponseBody
  public Object taskDetail(@PathVariable("instanceId") String instanceId, @PathVariable("taskId") String taskId, @PathVariable("service") String service) {
    if (service == null || taskId == null) return ResultView.error(ResultEnum.CODE_2);
    return ResultView.ok(usualWrokService.taskDetailMobile(service, taskId, instanceId));
  }

  /**
   * 审批进度
   */
  @PostMapping("/listHistory/{service}/{instanceId}")
  @ResponseBody
  public ResultView listHistory(@PathVariable("instanceId") String instanceId,
                                @PathVariable("service") String service,
                                HistoricActivity historicActivity) {

    ApproveProcessVo approveProcessVo = usualWrokService.listHistory(instanceId, service, historicActivity);
    return ResultView.ok(approveProcessVo);
  }

  /**
   * 完成任务
   *
   * @param approved: 1表示同意  0 表示驳回 -1 表示拒绝
   * @return
   */
  @RequestMapping(value = "/complete/{service}/{taskId}", method = {RequestMethod.POST, RequestMethod.GET})
  @ResponseBody
  public ResultView complete(@PathVariable("taskId") String taskId,
                             @PathVariable("service") String service,
                             @RequestParam(required = true) String loginName,
                             @RequestParam(required = true) String instanceId,
                             @RequestParam(required = false) String comment,
                             @RequestParam(required = true) Integer approved,
                             @RequestParam(required = false) String suspendState,
                             @RequestParam(required = false) String frontAssign,
                             HttpServletRequest request) {
//    if (approved == 1 || approved == -1) {
//      if (StringUtils.isEmpty(comment)) return ResultView.error(ResultEnum.CODE_2);
//    }
    usualWrokService.complete(
      loginName,
      taskId,
      instanceId,
      "repair_titile",
      "reason",
      "repair",
      approved,
      comment,
      service,
      request,
      suspendState,
      frontAssign);
    return ResultView.ok("任务已完成");
  }

  /**
   * 重新提交、废弃
   */
  @RequestMapping(value = "/reCommit/{service}/{taskId}/{instanceId}/{loginName}", method = {RequestMethod.POST, RequestMethod.GET})
  @ResponseBody
  public ResultView reCommit(@PathVariable("taskId") String taskId,
                             @PathVariable("service") String service,
                             @PathVariable("loginName") String loginName,
                             @PathVariable("instanceId") String instanceId,
                             @RequestParam String modifyEntity,
                             @RequestParam Integer approved ,
                             HttpServletRequest request) {

    usualWrokService.reCommit(loginName, service, taskId,
      instanceId, modifyEntity, approved,request);

    return ResultView.ok("任务已完成");
  }

  /**
   * 委托
   */
  @PostMapping("/delegate/{instanceId}/{taskId}/{loginName}/{delegateToUser}")
  @ResponseBody
  public ResultView delegate(
    @PathVariable("instanceId") String instanceId,
    @PathVariable("taskId") String taskId,
    @PathVariable("loginName") String loginName,
    @PathVariable("delegateToUser") String delegateToUser
  ) {
    usualWrokService.delegate(taskId, instanceId, loginName, delegateToUser);
    return ResultView.ok("委托完成..");
  }

  /**
   * 撤回审批
   */
  @PostMapping("/cancelApply/{service}/{instanceId}/{entityId}")
  @ResponseBody
  public ResultView cancelApply(
    @PathVariable("service") String service,
    @PathVariable("instanceId") String instanceId,
    @PathVariable("entityId") String entityId) {
    usualWrokService.cancelApply(service, instanceId, entityId);
    return ResultView.ok("撤销完成");
  }

  /**
   * 挂起
   */
  @PostMapping("/suspendOrActiveApply")
  @ResponseBody
  public AjaxResult suspendOrActiveApply(String instanceId, String suspendState) {
    processService.suspendOrActiveApply(instanceId, suspendState);
    return success();
  }

  /**
   * 抄送
   */
  @PostMapping("/addApplyCopy/{service}/{instanceId}/{loginNameSender}")
  @ResponseBody
  public ResultView addApplyCopy(
    @PathVariable("service") String service,
    @PathVariable("instanceId") String instanceId,
    @PathVariable("loginNameSender") String loginNameSender,
    @RequestParam String loginNameReceivers,
    String copyComment
  ) {
    usualWrokService.addApplyCopy(instanceId, service, loginNameSender, copyComment, loginNameReceivers);
    return ResultView.ok("抄送完成");
  }

}
